<template>
	<view class="article">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">{{post._id?'编辑':'新增'}}文章</block>
		</cu-custom>
		<!-- 文章基本信息维护 -->
		<form @submit="formClassifySubmit">
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class='action'>
					<text class='icon-titles text-orange '></text>
					文章标题
				</view>
			</view>
			<view class="cu-form-group align-start">
				<textarea id="postTitle" :value='post.title' placeholder="请输入文章标题" maxlength="-1"
					@blur="changePostDetail"></textarea>
			</view>
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class='action'>
					<text class='icon-titles text-orange '></text>
					文章链接
				</view>
			</view>
			<view class="cu-form-group align-start">
				<textarea id="postOriginalUrl" :value='post.originalUrl' placeholder="请输入文章链接" maxlength="-1"
					@blur="changePostDetail"></textarea>
			</view>
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class='action'>
					<text class='icon-titles text-orange '></text>
					文章摘要
				</view>
			</view>
			<view class="cu-form-group">
				<textarea id="postDigest" :value='post.digest' placeholder="一句话介绍" maxlength="-1"
					placeholder-class='placeholder' @blur="changePostDetail"></textarea>
			</view>
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class='action'>
					<text class='icon-titles text-orange '></text>
					文章封面
				</view>
			</view>
			<view v-if="imgList.length>0" class="cu-card dynamic no-card">
				<view class="cu-item shadow solids-bottom padding-bottom">
					<view class="grid col-1 flex-sub padding-lr">
						<view class="bg-img only-img text-right" :style="{backgroundImage:'url('+imgList[0]+')'}">
							<view class="cu-tag bg-red" @click.stop="DelImg" :data-index="index">
								<text class="cuIcon-close"></text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-if="imgList.length===0" class="cu-form-group padding-top">
				<view class="grid col-4  grid-square flex-sub">
					<view class="solids" @tap="ChooseImage">
						<text class="cuIcon-cameraadd"></text>
					</view>
				</view>
			</view>
			<!-- 文章详情维护（富文本） -->
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class='action'>
					<text class='icon-titles text-orange '></text>
					文章内容
				</view>
			</view>
			<view class="container bg-white">
				<view class="page-body">
					<view class='wrapper'>
						<view class='toolbar' @tap="format">
							<i class="iconfont icon-zitijiacu" :class="formats.bold ? 'ql-active' : ''"
								data-name="bold"></i>
							<i class="iconfont icon-zitixieti" :class="formats.italic ? 'ql-active' : ''"
								data-name="italic"></i>
							<i class="iconfont icon-zitixiahuaxian" :class="formats.underline ? 'ql-active' : ''"
								data-name="underline"></i>
							<i class="iconfont icon-zitishanchuxian" :class="formats.strike ? 'ql-active' : ''"
								data-name="strike"></i>
							<i class="iconfont icon-zuoduiqi" :class="formats.align === 'left' ? 'ql-active' : ''"
								data-name="align" data-value="left"></i>
							<i class="iconfont icon-juzhongduiqi" :class="formats.align === 'center' ? 'ql-active' : ''"
								data-name="align" data-value="center"></i>
							<i class="iconfont icon-youduiqi" :class="formats.align === 'right' ? 'ql-active' : ''"
								data-name="align" data-value="right"></i>
							<i class="iconfont icon-zuoyouduiqi" :class="formats.align === 'justify' ? 'ql-active' : ''"
								data-name="align" data-value="justify"></i>
							<i class="iconfont icon-line-height" :class="formats.lineHeight ? 'ql-active' : ''"
								data-name="lineHeight" data-value="2"></i>
							<i class="iconfont icon-Character-Spacing" :class="formats.letterSpacing ? 'ql-active' : ''"
								data-name="letterSpacing" data-value="2em"></i>
							<i class="iconfont icon-722bianjiqi_duanqianju"
								:class="formats.marginTop ? 'ql-active' : ''" data-name="marginTop"
								data-value="20px"></i>
							<i class="iconfont icon-723bianjiqi_duanhouju"
								:class="formats.micon-previewarginBottom ? 'ql-active' : ''" data-name="marginBottom"
								data-value="20px"></i>
							<i class="iconfont icon-clearedformat" @tap="removeFormat"></i>
							<i class="iconfont icon-font" :class="formats.fontFamily ? 'ql-active' : ''"
								data-name="fontFamily" data-value="Pacifico"></i>
							<i class="iconfont icon-fontsize" :class="formats.fontSize === '24px' ? 'ql-active' : ''"
								data-name="fontSize" data-value="24px"></i>
							<i class="iconfont icon-text_color" :class="formats.color === '#0000ff' ? 'ql-active' : ''"
								data-name="color" data-value="#0000ff"></i>
							<i class="iconfont icon-fontbgcolor"
								:class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
								data-name="backgroundColor" data-value="#00ff00"></i>
							<i class="iconfont icon-date" @tap="insertDate"></i>
							<i class="iconfont icon--checklist" data-name="list" data-value="check"></i>
							<i class="iconfont icon-youxupailie" :class="formats.list === 'ordered' ? 'ql-active' : ''"
								data-name="list" data-value="ordered"></i>
							<i class="iconfont icon-wuxupailie" :class="formats.list === 'bullet' ? 'ql-active' : ''"
								data-name="list" data-value="bullet"></i>
							<i class="iconfont icon-undo" @tap="undo"></i>
							<i class="iconfont icon-redo" @tap="redo"></i>
							<i class="iconfont icon-outdent" data-name="indent" data-value="-1"></i>
							<i class="iconfont icon-indent" data-name="indent" data-value="+1"></i>
							<i class="iconfont icon-fengexian" @tap="insertDivider"></i>
							<i class="iconfont icon-charutupian" @tap="insertImage"></i>
							<i class="iconfont icon-format-header-1" :class="formats.header === 1 ? 'ql-active' : ''"
								data-name="header" :data-value="1"></i>
							<i class="iconfont icon-zitixiabiao" :class="formats.script === 'sub' ? 'ql-active' : ''"
								data-name="script" data-value="sub"></i>
							<i class="iconfont icon-zitishangbiao"
								:class="formats.script === 'super' ? 'ql-active' : ''" data-name="script"
								data-value="super"></i>
							<!-- <i class="iconfont icon-quanping"></i> -->
							<i class="iconfont icon-shanchu" @tap="clear"></i>
							<i class="iconfont icon-direction-rtl"
								:class="formats.direction === 'rtl' ? 'ql-active' : ''" data-name="direction"
								data-value="rtl"></i>
						</view>
						<editor id="editor" class="ql-container" :placeholder="placeholder" showImgSize showImgToolbar
							showImgResize @statuschange="onStatusChange" :read-only="readOnly" @ready="onEditorReady">
						</editor>
					</view>
				</view>
			</view>
			<view style="padding:50rpx"></view>
			<!-- 文章详情维护（底部保存按钮） -->
			<view class='box'>
				<view class="cu-bar foot bg-white tabbar border shop">
					<view class="action" @tap="showArticleList">
						<view class="icon-back"></view>
						返回
					</view>
					<view class="action" @tap="clearAll">
						<view class="icon-delete"></view>
						全部清空
					</view>
					<view class="bg-orange submit" @tap="savePostExceptContent">除内容以外保存</view>
					<view class="bg-green submit" @tap="savePost">全部保存</view>
				</view>
			</view>
		</form>
		<!-- 保存成功后窗口 -->
		<view :class="isShowModel?'cu-modal show':'cu-modal'">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class='content'>保存完成</view>
					<view class='action' @tap='hideShowModal'>
						<text class='icon-close text-red'></text>
					</view>
				</view>
				<view class='padding-xl'>文章已经处理成功啦～</view>
				<view class="cu-bar bg-white">
					<view class='action margin-0 flex-sub  solid-left' @tap='hideShowModal'>留在本页</view>
					<view class='action margin-0 flex-sub text-green solid-left' @tap='showArticleList'>
						返回列表
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import util from '../../utils/util.js';
	import api from '../../utils/api.js';
	import config from '../../utils/config.js';
	export default {
		data() {
			return {
				imgUrl: getApp().globalData.imgUrl,
				placeholder: "赶快创作你的作品吧...",
				post: {},
				imgList: [],
				isShowModel: false
			};
		},
		onLoad: async function(options) {
			let that = this;
			let blogId = options.id;

			console.info(blogId);

			uni.createSelectorQuery().select('#editor').context(function(res) {
				that.editorCtx = res.context;
			}).exec();
			if (blogId !== undefined) {
				let result = await api.getPostsById(blogId);
				that.post = result.data;
				that.imgList = that.imgList.concat(result.data.defaultImageUrl);

				that.editorCtx.setContents({
					html: result.data.content,
					success: (res) => {
						console.log(res);
					},
					fail: (res) => {
						console.log(res);
					}
				});
			}
		},
		methods: {
			onEditorReady: function() {
				// let _this=this;
				// uni.createSelectorQuery().in(this).select('#editor').context((res) => {
				// 	res.context.setContents({
				// 		html: _this.post.content
				// 	})
				// 	this.editorCtx = res.context
				// }).exec()
			},
			/**
			 * 文章变化
			 * @param {*} e
			 */
			changePostDetail(e) {
				let that = this;
				let post = that.post;
				console.info(e)
				switch (e.target.id) {
					case 'postTitle': {
						post.title = e.detail.value;
						break
					}
					case 'postClassify': {
						post.classify = e.detail.value;
						break
					}
					case 'postDigest': {
						post.digest = e.detail.value;
						break
					}
					case 'postOriginalUrl': {
						post.originalUrl = e.detail.value;
						break
					}
				}

				that.post = post;
			},
			/**
			 * 除内容之外保存
			 * @param {*} e
			 */
			async savePostExceptContent(e) {
				let that = this;
				let post = that.post;

				if (post._id === undefined) {
					uni.showToast({
						title: '更新时才能点哦',
						icon: 'none',
						duration: 1500
					})
					return;
				}

				uni.showLoading({
					title: '保存中...'
				})

				let res = await this.getContent()

				let newPost = {
					digest: post.digest, //摘要
					title: post.title,
					originalUrl: post.originalUrl,
					timestamp: new Date().getTime()
				}

				let result = await api.upsertPosts(post._id === undefined ? "" : post._id, newPost);
				if (result.result) {
					uni.hideLoading();
					that.isShowModel = true;
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '保存失败',
						icon: 'none',
						duration: 1500
					});
				}
			},
			/**
			 * 保存文章
			 * @param {*} e
			 */
			async savePost(e) {
				uni.showLoading({
					title: '保存中...',
				})

				let that = this;
				let post = that.post;
				if (post.title === undefined || post.title == "") {
					uni.showToast({
						title: '标题不能为空',
						icon: 'none',
						duration: 1500
					})
					return;
				}

				let res = await this.getContent();
				let newPost;
				if (post._id === undefined) {
					let img = "";
					if (that.imgList.length > 0) {
						let filePath = that.imgList[0];
						img = await this.getTempUrl(filePath);
					}
					newPost = {
						uniqueId: "",
						sourceFrom: "admin",
						author: "博主",
						title: post.title,
						defaultImageUrl: img,
						createTime: util(parseInt(new Date().getTime()), 6),
						timestamp: new Date().getTime(),
						totalComments: 0, //总的点评数
						totalVisits: 200 + Math.floor(Math.random() * 40), //总的访问数
						totalZans: 10 + Math.floor(Math.random() * 40), //总的点赞数
						label: [], //标签
						classify: 0, //分类
						contentType: "html",
						digest: post.digest, //摘要
						isShow: 0, //是否展示
						originalUrl: "",
						content: res,
						totalCollection: 10 + Math.floor(Math.random() * 40)
					};
				} else {
					newPost = {
						digest: post.digest, //摘要
						title: post.title,
						timestamp: new Date().getTime(),
						content: res.html,
						originalUrl: post.originalUrl
					};
				}

				let result = await api.upsertPosts(post._id === undefined ? "" : post._id, newPost);
				if (result.result) {
					uni.hideLoading()
					that.isShowModel = true;
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '保存失败',
						icon: 'none',
						duration: 1500
					});
				}
			},
			undo() {
				this.editorCtx.undo();
			},
			redo() {
				this.editorCtx.redo();
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset;
				if (!name) return;
				// console.log('format', name, value)
				this.editorCtx.format(name, value);

			},
			onStatusChange(e) {
				this.formats = e.detail;
			},
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success');
					}
				});
			},
			clear() {
				this.editorCtx.clear({
					success: function(res) {
						console.log("clear success");
					}
				});
			},
			removeFormat() {
				this.editorCtx.removeFormat();
			},
			insertDate() {
				const date = new Date();
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
				this.editorCtx.insertText({
					text: formatDate
				});
			},
			insertImage: async function() { //插入图片
				let that = this;
				uni.chooseImage({
					count: 6,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: (res) => {
						const tasks = [];
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							const promise = that.getTempUrl(res.tempFilePaths[i]);
							tasks.push(promise);
						}
						Promise.all(tasks).then((result) => {
							console.info(result);
							for (let i = 0; i < result.length; i++) {
								that.editorCtx.insertImage({
									src: result[i],
									alt: '图像',
									success: function() {
										console.log('insert image success')
									}
								})
							}
						}).catch((error) => {
							console.err(error)
						})
					}
				})
			},
			getTempUrl: async function(filePath) { //插入图片
				let src = '';
				let suffix = /\.[^\.]+$/.exec(filePath)[0];
				const cloudPath = 'images/editor/' + new Date().getTime() + suffix;
				let imgRes = await api.uploadFile(cloudPath, filePath);
				if (imgRes.errMsg == 'cloud.uploadFile:ok') {
					let file = await api.getTempUrl(imgRes.fileID);
					if (file.errMsg == 'cloud.getTempFileURL:ok') {
						src = file.fileList[0].tempFileURL;
					}
				};
				return src;
			},
			/**
			 * 获取富文本内容
			 */
			getContent() {
				let that = this
				return new Promise((resolve, rej) => {
					that.editorCtx.getContents({
						success: (res) => {
							resolve(res.html);
						},
						fail: res => {
							console.log("请求失败");
						}
					});
				})
			},
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths);
						} else {
							this.imgList = res.tempFilePaths;
						}
					}
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '删除图片',
					content: '确定要删除该图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1);
						}
					}
				});
			},
			/**
			 * 设置隐藏
			 * @param {*} e
			 */
			hideShowModal(e) {
				this.post = {};
				this.imgList = [];
				this.isShowModel = false;
			},
			showArticleList(e) {
				uni.navigateBack({
					delta: 1
				});
			},
			clearAll(e) {
				this.post = {};
				this.imgList = [];
			}
		},
	};
</script>

<style>
	@import "../../static/jyf-parser/iconfont.css";
	@import "../../static/jyf-parser/editor.css";

	.container {
		display: flex;
		flex-direction: column;
		min-height: 100%;
		justify-content: space-between;
		font-size: 32rpx;
		font-family: -apple-system-font, Helvetica Neue, Helvetica, sans-serif;
	}

	.page-body {
		width: 100%;
		flex-grow: 1;
		overflow-x: hidden;
	}

	.page-body-wrapper {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 40px;
		height: 40px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}


	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		min-height: 30vh;
		height: auto;
		background: #fff;
		margin-top: 20px;
		font-size: 16px;
		line-height: 1.5;
	}

	.ql-active {
		color: #06c;
	}
</style>
